package com.tensquare.user.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;
import com.tensquare.util.JwtUtil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;

import com.tensquare.dto.PageResult;
import com.tensquare.dto.Result;
import com.tensquare.dto.StatusCode;
/**
 * user控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Autowired
	private JwtUtil jwtUtil;
	
	@Autowired
	private HttpServletRequest request;
	
	
	/**
	 * 删除
	 * 
	 * 1、鉴权：如果是admin 才可以删除
	 * 2、如果不是admin，提醒权限不足
	 * 
	 * 
	 * @param id
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id ){
		/*//获取token
		String auth = request.getHeader("Authorization");
		System.out.println("auth:"+auth);
		
		//解析token
		Claims parseJWT = null;
		if(auth.startsWith("Bearer ")) {
			try {
				parseJWT = jwtUtil.parseJWT(auth.substring(7));
			} catch (ExpiredJwtException e) {
				System.out.println("token过期了："+e.getMessage());
				return new Result(false,StatusCode.ACCESS_ERROR,"token已过期，请重新登录！");
			} catch (Exception e) {
				System.out.println("解析jwt异常："+e.getMessage());
				return new Result(false,StatusCode.ACCESS_ERROR,"非法token，请不要搞我！");
			}
		}
		//查看用户是否是管理员
		if(parseJWT==null || !"admin".equals(parseJWT.get("roles"))) {
			return new Result(false,StatusCode.ACCESS_ERROR,"权限不足！");
		}*/
		
		Claims parseJWT = (Claims) request.getAttribute("admin_Claims");
		//权限判断
		if(parseJWT==null || !"admin".equals(parseJWT.get("roles"))) {
			return new Result(false,StatusCode.ACCESS_ERROR,"权限不足！");
		}
		
		userService.deleteById(id);
		return new Result(true,StatusCode.OK,"删除成功");
	}
	
	/**
	 * 用户登录
	 * @param user
	 * @return
	 */
	@PostMapping("/login")
	public Result login(@RequestBody User user){
		User loginUser = userService.login(user);
		if(loginUser==null) {
			return new Result(false,StatusCode.USER_PASS_ERROR,"登录失败，用户名或者密码错误！");
		}
		//返回用户的一些认证的信息
		//可以登录:  返回给前端token、用户的名称、用户的头像
		Map<String,String> user2 = new HashMap<String,String>();
		user2.put("name", loginUser.getNickname());
		user2.put("avatar","http://git.cfei.net/avatars/2");
		user2.put("token", jwtUtil.createJWT(loginUser.getId(), loginUser.getNickname(), "user"));
				
		
		return new Result(true,StatusCode.OK,"用户登录成功！",user2);
	}

	/**
	 * 用户注册
	 * @param code
	 * @param user
	 * @return
	 */
	@PostMapping("/register/{code}")
	public Result register(@PathVariable String code,@RequestBody User user){
		userService.register(code,user);
		return new Result(true,StatusCode.OK,"恭喜：用户注册成功，请妥善保管你的账号和密码");
	}


	/**
	 * 发送短信验证码
	 * @param mobile
	 * @return
	 */
	@PostMapping("/sendsms/{mobile}")
	public Result sendsms(@PathVariable String mobile){
		userService.sendsms(mobile);
		return new Result(true,StatusCode.OK,"发送短信验证码成功！");
	}
	
	
	/**
	 * 查询全部数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	
	/**
	 * 增加
	 * @param user
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody User user  ){
		userService.add(user);
		return new Result(true,StatusCode.OK,"增加成功");
	}
	
	/**
	 * 修改
	 * @param user
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.PUT)
	public Result update(@RequestBody User user, @PathVariable String id ){
		user.setId(id);
		userService.update(user);		
		return new Result(true,StatusCode.OK,"修改成功");
	}

	
}
